# !/usr/bin/env python
# -*- coding:utf-8 -*-
# project name: esp8266_universal_control
# author: "Lei Yong" 
# creation time: 2024-07-03 15:24
# Email: leiyong711@163.com


import os
import gc

if 'machine.mpy' in os.listdir():
    try:
        os.remove('machine.mpy')
    except:
        ...

from run import boot_main
from tools import show_time


gc.enable()
# Pin(14, Pin.OUT).value(0)
# Pin(13, Pin.OUT).value(0)
gc.collect()


def init_io_recovery():
    import io
    import gc
    import json
    import sys
    from log import Logger
    from machine import Pin
    lg = Logger()
    gc.collect()
    try:
        with open('io_state.ini', 'r') as f:
            io_state = json.loads(f.read())
    except:
        io_state = {}
    gc.collect()
    for k, v in io_state.items():
        if v.get('type') == 'color_switch':
            try:
                from tools import ws2812
                if isinstance(v.get('v'), int):
                    if v.get('v') == 0:
                        ws2812(pin=k, number=8, color=(0, 0, 0), shut_down=True)
                        Pin(int(k), Pin.OUT).value(v.get('v'))
                    return

                # 判断cmd是否为json格式
                v_v = v.get('v', {})
                ws2812(pin=int(k), number=8, color=(int(v_v.get('r', 0)), int(v_v.get('g', 0)), int(v_v.get('b', 0))))
            except Exception as e:
                buf = io.StringIO()
                sys.print_exception(e, buf)
                err = buf.getvalue()
                err_log = f"LED灯控制错误，原因：\n{err}"
                print(f"{show_time()} {err_log}")
                lg.log(err_log)
        else:
            print(f"{show_time()} 将 Pin{k} 初始化设置为 {v.get('v')} ")
            Pin(int(k), Pin.OUT).value(int(v.get('v')))
        gc.collect()
    gc.collect()


def main():
    boot_main()


if __name__ == '__main__':
    main()

